package com.cvicse.jrcompetition01.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cvicse.jrcompetition01.common.exception.BusinessException;
import com.cvicse.jrcompetition01.common.exception.BusinessExceptionEnum;
import com.cvicse.jrcompetition01.common.lang.Result;
import com.cvicse.jrcompetition01.controller.form.InsertMechanismForm;
import com.cvicse.jrcompetition01.entity.Mechanism;
import com.cvicse.jrcompetition01.entity.MechanismDepartment;
import com.cvicse.jrcompetition01.entity.dto.MechanismDto;
import com.cvicse.jrcompetition01.mapper.MechanismDepartmentMapper;
import com.cvicse.jrcompetition01.mapper.MechanismMapper;
import com.cvicse.jrcompetition01.utils.AutoGenerateCodeUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 作者:kissshotwang@163.com
 * @since 2022-07-21
 */
@RestController
@RequestMapping("/mechanism")
public class MechanismController extends BaseController {

    @Resource
    MechanismMapper mechanismMapper;

    @Resource
    MechanismDepartmentMapper mechanismDepartmentMapper;


    @GetMapping("/mechanismList")
    public Result mechanismList(String mechanismName) {
        IPage iPage = mechanismMapper.selectPageVo(getPage(), mechanismName);
        return Result.succ(iPage);
    }

    @PostMapping("/add")
    @Transactional
    public Result add(@RequestBody InsertMechanismForm insertMechanismForm) {
        mechanismService.add(insertMechanismForm);
        return Result.succ("恭喜你，操作成功");
    }

    @PostMapping("/delete")
    @Transactional
    public Result delete(@RequestBody Long[] ids) {
        //Arrays.asList() 数组转列表 因为mybatis-plus的removeByIds方法参数是list类型
        List<Long> idList = new ArrayList<Long>(Arrays.asList(ids));
        //中间表的记录删除
        for (Long id : idList
        ) {
            mechanismDepartmentMapper.delete(new QueryWrapper<MechanismDepartment>().eq("mechanism_id",id));
        }
        mechanismService.removeByIds(idList);
        return Result.succ("恭喜你，操作成功");
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        MechanismDto mechanismDto = mechanismService.info(id);
        return Result.succ(mechanismDto);
    }

    @PostMapping("/update")
    @Transactional
    public Result update(@RequestBody MechanismDto mechanismDto ) {
        mechanismService.update(mechanismDto);
        return Result.succ("恭喜你，操作成功");
    }

}
